﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using ZBJF.Warranty.Model.ViewModel.Sellers;

namespace ZBJF.Warranty.BLL
{
    public partial class SellerInsuranceProductsService
    {
        public SellerInsuranceProducts LoadById(long sllerInsuranceProductsId)
        {
            return LoadEntities(o => o.ID == sllerInsuranceProductsId).FirstOrDefault();
        }



        public bool IsExist(string productName, long id = 0)
        {
            var expressionWhere = PredicateExtensions.True<SellerInsuranceProducts>();
            expressionWhere = expressionWhere.And(o => o.ProductName.Equals(productName));
            if (id != 0)
                expressionWhere = expressionWhere.And(o => o.ID != id);
            return LoadEntities(expressionWhere).Any();
        }
        public IQueryable<SellerInsuranceProducts> GetPagingList(SellerInsuranceProductsModel model, out int total)
        {
            var expressionWhere = PredicateExtensions.True<SellerInsuranceProducts>();
            if (!string.IsNullOrEmpty(model.Keyword))
            {
                expressionWhere = expressionWhere.And(o => o.ProductName.Equals(model.Keyword, StringComparison.CurrentCultureIgnoreCase));
            }
            if (model.IsAvailable.HasValue)
            {
                expressionWhere = expressionWhere.And(c => c.IsAvailable == model.IsAvailable);
            }
            if (!string.IsNullOrWhiteSpace(model.ProductName))
            {
                expressionWhere = expressionWhere.And(o => o.ProductName.Contains(model.ProductName.Trim()));
            }
            if (model.IsCardProduct.HasValue)
            {
                //获取保险卡产品，并且销量不能超过限制的量
                expressionWhere = expressionWhere.And(o => o.IsCardProduct);
            }
            if (model.SellerId.HasValue)
            {
                expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductMappings.Where(s => s.SellerInsuranceProducts.SellerId == model.SellerId.Value && s.SellerInsuranceProducts.IsAvailable).Select(p => p.SellerInsuranceProductId).Contains(o.ID));
            }
            if (model.CreateTimeStart.HasValue)
            {
                //获取保险卡产品，并且销量不能超过限制的量
                expressionWhere = expressionWhere.And(o => o.CreateTime >= model.CreateTimeStart);
            }
            if (model.CreateTimeEnd.HasValue)
            {
                //获取保险卡产品，并且销量不能超过限制的量
                expressionWhere = expressionWhere.And(o => o.CreateTime < SqlFunctions.DateAdd("dd", 1, model.CreateTimeEnd));
            }
            if (model.ProductAmount > 0)//返回的产品价格，联通销售产品会返回此字段，只获取非卡产品
            {
                var insuranceProductIds = ServiceFactory.InsuranceProductsServiceInstance.GetInsuranceProductsInPointAmount(model.ProductAmount);
                expressionWhere = expressionWhere.And(p => p.SellerInsuranceProductMappings.Where(s => insuranceProductIds.Contains(s.InsuranceProductId.Value)).Select(m => m.SellerInsuranceProductId).Contains(p.ID));
            }
            if (!string.IsNullOrWhiteSpace(model.Name))
            {
                expressionWhere = expressionWhere.And(o => o.Sellers.SellersName.Contains(model.Name) || o.ProductName.Contains(model.Name));
            }
            if (string.IsNullOrWhiteSpace(model.iSorts))
            {
                model.iSorts = "CreateTime desc";
            }

            return LoadPagerEntities<SellerInsuranceProducts>(model.PageIndex, model.iDisplayLength, out total, expressionWhere, model.iSorts);
        }


        #region 获取销售商产品可承保条件信息_用于尺度（一个产品一个服务项目） + SellerInsuranceProductsAvailableInfo GetAvailableInfo(string sellerCode, long sellerInsuranceProductsId)
        /// <summary>
        /// 获取销售商产品可承保条件信息_用于尺度（一个产品一个服务项目）
        /// </summary>
        /// <param name="sellerCode">销售商编码</param>
        /// <param name="sellerInsuranceProductsCode">销售商产品编码</param>
        /// <returns></returns>
        public SellerInsuranceProductsAvailableInfo GetAvailableInfo(string sellerCode, string sellerInsuranceProductsCode)
        {
            if (string.IsNullOrEmpty(sellerCode) || string.IsNullOrEmpty(sellerInsuranceProductsCode))
                return null;

            //1、查询基础产品信息
            var cellPhoneServiceProject = (from a in ServiceFactory.SellersServiceInstance.LoadEntities(a => a.SellerCode == sellerCode)
                                           join b in ServiceFactory.SellerInsuranceProductsServiceInstance.LoadEntities(b => b.SellerProductCode == sellerInsuranceProductsCode) on a.ID equals b.SellerId
                                           join c in ServiceFactory.SellerInsuranceProductMappingsServiceInstance.LoadEntities(a => true) on b.ID equals c.SellerInsuranceProductId
                                           join d in ServiceFactory.InsuranceProductsServiceInstance.LoadEntities(a => true) on c.InsuranceProductId equals d.ID
                                           join e in ServiceFactory.CellPhoneServiceProjectServiceInstance.LoadEntities(a => true) on d.ID equals e.InsuranceProductsID
                                           select new
                                           {
                                               e.ID,
                                               e.UseModelTypeOption, //启用机型条件
                                               e.ModelTypeJudgeType,  //机型条件判断类型
                                               e.UseScreenTypeOption, //启用屏幕类型条件
                                               e.ScreenTypeJudgeType, //屏幕类型条件判断类型
                                               e.UsePriceOption,
                                               e.ProductAmountFrom,
                                               e.ProductAmountTo
                                           }).FirstOrDefault();
            if (cellPhoneServiceProject == null || cellPhoneServiceProject.ID < 1)
                return null;

            SellerInsuranceProductsAvailableInfo result = new SellerInsuranceProductsAvailableInfo();
            //适用价格条件
            if (cellPhoneServiceProject.UsePriceOption)
            {
                result.AvailablePrice = new AvailablePrice();
                result.AvailablePrice.AvailablePriceStart = cellPhoneServiceProject.ProductAmountFrom.HasValue ? cellPhoneServiceProject.ProductAmountFrom.Value.ToString() : "";
                result.AvailablePrice.AvailablePriceEnd = cellPhoneServiceProject.ProductAmountTo.HasValue ? cellPhoneServiceProject.ProductAmountTo.Value.ToString() : "";
            }
            //使用品牌、机型条件
            if (cellPhoneServiceProject.UseModelTypeOption)
            {
                var tempResult = (from d in ServiceFactory.InsuranceProductsAvailableModelTypeServiceInstance.LoadEntities(a => a.CellPhoneServiceProjectID == cellPhoneServiceProject.ID)
                                  join e in ServiceFactory.ProductModelsServiceInstance.LoadEntities(a => true) on d.ModelID equals e.ID
                                  join f in ServiceFactory.ProductBrandsServiceInstance.LoadEntities(a => true) on e.BrandId equals f.ID
                                  select new
                                  {
                                      e.ID,
                                      e.ModelName,
                                      e.BrandId,
                                      f.BrandName
                                  }).ToList();
                if (tempResult == null || tempResult.Count < 1)
                    return null;
                List<BrandInfo> brandInfo = tempResult.GroupBy(t => new { t.BrandId, t.BrandName }).Select(t => new BrandInfo()
                {
                    BrandId = t.Key.BrandId,
                    BrandName = t.Key.BrandName
                }).ToList();
                foreach (BrandInfo item in brandInfo)
                {
                    item.AvailableModels = tempResult.Where(t => t.BrandId == item.BrandId).Select(t => new ModelInfo { ModelId = t.ID, ModelName = t.ModelName }).ToList();
                }
                result.AvailableBrands = brandInfo;
            }
            //使用屏幕类型条件
            if (cellPhoneServiceProject.UsePriceOption)
            {
                result.AvailableScreenType = ServiceFactory.InsuranceProductsAvailableScreenTypeServiceInstance.LoadEntities(t => t.CellPhoneServiceProjectID == cellPhoneServiceProject.ID)
                                            .Select(t => new ScreenTypeInfo()
                                            {
                                                ScreenTypeCode = t.ScreenTypeCode,
                                                //ScreenTypeName = EnumHelper.Instance.GetDescription(typeof(ScreenTypeEnum), t.ScreenTypeCode)
                                            }).ToList();
                foreach (var item in result.AvailableScreenType)
                {
                    item.ScreenTypeName = EnumHelper.Instance.GetDescription(typeof(ScreenTypeEnum), item.ScreenTypeCode);
                }
            }
            return result;
        }
        #endregion

        #region 判断投保信息是否可承保_用于尺度（一个产品一个服务项目） + bool VerifyAcceptable(string sellerCode, long sellerInsuranceProductsId, long modelId, decimal equipmentPrice, byte screenTypeCode, out string message)
        /// <summary>
        /// 判断投保信息是否可承保_用于尺度（一个产品一个服务项目）
        /// </summary>
        /// <param name="sellerCode">销售商编码</param>
        /// <param name="sellerInsuranceProductsId">销售商产品ID</param>
        /// <param name="modelId">型号ID</param>
        /// <param name="equipmentPrice">设备价格</param>
        /// <param name="screenTypeCode">屏幕类型</param>
        /// <param name="message">错误消息</param>
        /// <returns></returns>
        public bool VerifyAcceptable(string sellerCode, long sellerInsuranceProductsId, long modelId, decimal equipmentPrice, byte screenTypeCode, out string message)
        {
            message = "";
            if (string.IsNullOrEmpty(sellerCode) || sellerInsuranceProductsId < 1)
            {
                message = "销售商编码和销售商产品ID不能为空";
                return false;
            }

            //1、查询基础产品服务项目信息
            var cellPhoneServiceProject = (from a in ServiceFactory.SellersServiceInstance.LoadEntities(a => a.SellerCode == sellerCode)
                                           join b in ServiceFactory.SellerInsuranceProductsServiceInstance.LoadEntities(b => b.ID == sellerInsuranceProductsId) on a.ID equals b.SellerId
                                           join c in ServiceFactory.SellerInsuranceProductMappingsServiceInstance.LoadEntities(a => true) on b.ID equals c.SellerInsuranceProductId
                                           join d in ServiceFactory.InsuranceProductsServiceInstance.LoadEntities(a => true) on c.InsuranceProductId equals d.ID
                                           join e in ServiceFactory.CellPhoneServiceProjectServiceInstance.LoadEntities(a => true) on d.ID equals e.InsuranceProductsID
                                           select new
                                           {
                                               e.ID,
                                               e.UseModelTypeOption, //启用机型条件
                                               e.ModelTypeJudgeType,  //机型条件判断类型
                                               e.UseScreenTypeOption, //启用屏幕类型条件
                                               e.ScreenTypeJudgeType, //屏幕类型条件判断类型
                                               e.UsePriceOption,
                                               e.ProductAmountFrom,
                                               e.ProductAmountTo
                                           }).FirstOrDefault();
            if (cellPhoneServiceProject == null || cellPhoneServiceProject.ID < 1)
            {
                message = "未查询到产品信息";
                return false;
            }

            //使用价格条件
            if (cellPhoneServiceProject.UsePriceOption)
            {
                decimal start = cellPhoneServiceProject.ProductAmountFrom.HasValue ? cellPhoneServiceProject.ProductAmountFrom.Value : 0;
                decimal end = cellPhoneServiceProject.ProductAmountTo.HasValue ? cellPhoneServiceProject.ProductAmountTo.Value : 0;
                if (equipmentPrice < start || equipmentPrice > end)
                {
                    message = "不满足承保价格条件";
                    return false;
                }
            }
            //使用品牌、机型条件
            if (cellPhoneServiceProject.UseModelTypeOption)
            {
                var tempResult = ServiceFactory.InsuranceProductsAvailableModelTypeServiceInstance.LoadEntities(a => a.CellPhoneServiceProjectID == cellPhoneServiceProject.ID && a.ModelID == modelId).FirstOrDefault();
                if (tempResult == null || tempResult.ID < 1)
                {
                    message = "不满足承保型号条件";
                    return false;
                }
            }

            //使用屏幕类型条件
            if (cellPhoneServiceProject.UsePriceOption)
            {
                var tempScreen = ServiceFactory.InsuranceProductsAvailableScreenTypeServiceInstance.LoadEntities(t => t.CellPhoneServiceProjectID == cellPhoneServiceProject.ID && t.ScreenTypeCode == screenTypeCode).FirstOrDefault();
                if (tempScreen == null || tempScreen.ID < 1)
                {
                    message = "不满足承保屏幕类型条件";
                    return false;
                }
            }

            return true;
        }
        #endregion

        #region  获取销售商产品ID
        /// <summary>
        /// 获取销售商产品ID
        /// </summary>
        /// <param name="sellerInsuranceProductsCode">销售商产品编码</param>
        /// <returns></returns>
        public SellerInsuranceProductsInfo GetSellerInsuranceProductsId(string sellerInsuranceProductsCode)
        {

            var item = (from a in LoadEntities(t => t.SellerProductCode == sellerInsuranceProductsCode)
                        join b in ServiceFactory.InsuranceCompanyServiceInstance.LoadEntities(t => true) on a.InsuranceCompanyID equals b.ID into temp
                        from c in temp.DefaultIfEmpty()
                        join d in ServiceFactory.InsuranceCompanyServiceInstance.LoadEntities(t => true) on c.ParentID equals d.ID into temp1
                        from e in temp1.DefaultIfEmpty()
                        select new SellerInsuranceProductsInfo
                        {
                            SellerInsuranceProductsID = a.ID,
                            InsuranceCompanyID = c.ID,
                            ParentInsuranceCompanyName = c.ParentCompanyName,
                            InsuranceCompanyName = c.CompanyName,
                            CompanyID = e.ID,
                            ZBJFSalePrice = a.ZBJFSalePrice,
                            SaleRetailPrice = a.SaleRetailPrice,
                            InsuranceCompanyRetailPrice = a.InsuranceCompanyRetailPrice
                        }).ToList().FirstOrDefault();

            return item;
        }
        #endregion
    }
}
